package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Regla;
import service.ServiceProvider;

//ABM de Reglas

public class ReglaServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String idStr = req.getParameter("delid");
		
		if (idStr != null){
			ServiceProvider.getDao().borrarRegla(Integer.parseInt(idStr));
		}
		
		mostrarRespuesta(req, resp);		
        
	}
	
	private void mostrarRespuesta(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		List<Regla> reglas = ServiceProvider.getDao().getReglas();
		
        PrintWriter out = resp.getWriter();		
        out.println("<HEAD><TITLE>Reglas</TITLE></HEAD><BODY>");
        out.println("<a href=\"/tpfinal\">Menu</a>");
        out.println("<form action=\"ReglaServlet\" method=\"POST\">");
        out.println("Si ");        
        out.println("<input type=\"text\" name=\"ant\" >" );        
        out.println(" --> ");        
        out.println("<input type=\"text\" name=\"cons\" >" );
        out.println("<input type=\"Submit\" value=\"Agregar\" >" );        
        out.println("</form>");
		out.println("<table>");
        out.println("<tr><td>BORRAR</td><td>REGLA</td></tr>");
        
        for (Regla r : reglas){
        	out.println("<tr>");        	
            out.println("<td><form action=\"ReglaServlet\" method=\"GET\"><input type=\"Submit\" value=\"" + r.id + "\" name=\"delid\"></form></td>");
            
            String reglaStr = "Si " + r.ant;
            
            if (r.union != null){
            	reglaStr = reglaStr + " " + r.union + " " + r.ant1;
            }
            
            reglaStr = reglaStr + " --> " + r.cons;            
            
            out.println("<td>" + reglaStr + "</td>");
            out.println("</tr>");        	
        }
        
        out.println("</BODY>");
        out.close();		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String ant = req.getParameter("ant");
		String cons = req.getParameter("cons");
		
		if (ant != null && ant.trim().length() > 0){
			if (cons != null && cons.trim().length() > 0){
				Regla r = new Regla();
				r.ant = ant;
				r.cons = cons;
				ServiceProvider.getDao().saveRegla(r);
			}
		}
		
		mostrarRespuesta(req, resp);
	}

}
